package com.aiYouPms.common.validator;

import com.aiYouPms.common.annotations.ValidEnum;
import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;

import java.lang.reflect.Method;

public class EnumValidator implements ConstraintValidator<ValidEnum, Integer> {
    private Class<? extends Enum<?>> enumClass;

    @Override
    public void initialize(ValidEnum annotation) {
        this.enumClass = annotation.enumClass();
    }

    @Override
    public boolean isValid(Integer value, ConstraintValidatorContext context) {
        if (value == null) {
            return true; // 如果允许为null，则返回true
        }

        // 获取枚举类中定义的方法
        try {
            Method method = enumClass.getMethod("isValidCode", int.class);
            return (Boolean) method.invoke(null, value);
        } catch (Exception e) {
            // 如果没有isValidCode方法，则检查所有枚举值的code
            try {
                Method getCodeMethod = enumClass.getMethod("getCode");
                for (Object enumConstant : enumClass.getEnumConstants()) {
                    int code = (Integer) getCodeMethod.invoke(enumConstant);
                    if (code == value) {
                        return true;
                    }
                }
            } catch (Exception ex) {
                // 忽略异常
            }
            return false;
        }
    }
}
